package com.neoCalf.neoCommon.coreController;


import com.neoCalf.neoCommon.coreService.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AlipayController {
    @Autowired
    private AlipayService alipayService;

    @GetMapping("/pay")
    public String pay() {
        // 生成商户订单号（需保证唯一性）
        String outTradeNo = "ORDER_" + System.currentTimeMillis();
        return alipayService.createOrder(outTradeNo, "0.01", "测试商品"); // 直接返回表单自动跳转支付宝
    }

    @PostMapping("/notify")
    public String notifyUrl(HttpServletRequest request) {
        Map<String, String> params = convertRequestParams(request);

        if (alipayService.verifySignature(params)) {
            String tradeStatus = params.get("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                // 更新订单状态
                return "success";
            }
        }
        return "failure";
    }

    private Map<String, String> convertRequestParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        try {
            // 设置字符编码（防止中文乱码）
            request.setCharacterEncoding("UTF-8");
            // 获取所有参数Map
            Map<String, String[]> requestParams = request.getParameterMap();
            // 转换参数格式
            for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
                String paramName = entry.getKey();
                String[] paramValues = entry.getValue();
                // 支付宝规范要求保留空值参数
                String paramValue = (paramValues != null && paramValues.length > 0) ?
                        paramValues[0] : "";
                // 处理特殊字符（可选）
                paramValue = URLDecoder.decode(paramValue, "UTF-8");
                params.put(paramName, paramValue);
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("字符编码转换异常", e);
        }
        return params;
    }
}
